/*
 * ModifyLog.java
 *
 * Created on July 11, 2006, 10:04 AM
 */

package org.vcboard.view;

import java.awt.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import org.apache.log4j.*;
import org.vcboard.database.*;
import org.vcboard.event.*;
import org.vcboard.model.*;

/**
 *
 * @author  vanderl
 */
public class ModifyLog extends javax.swing.JFrame
      implements UserChangedListener
{
   private static Logger log = Logger.getLogger(ModifyLog.class);
   
   private static SpinnerNumberModel hourInSpinnerModel = new SpinnerNumberModel(0, 0, 23, 1);
   private static SpinnerNumberModel hourOutSpinnerModel = new SpinnerNumberModel(0, 0, 23, 1);
   private static SpinnerNumberModel minuteInSpinnerModel = new SpinnerNumberModel(0, 0, 59, 1);
   private static SpinnerNumberModel minuteOutSpinnerModel = new SpinnerNumberModel(0, 0, 59, 1);
   
   private TimeLog timeLog = null;
   
   private static final String[] monthNames = 
   {
      "January", "February", "March", "April", "May", "June",
      "July", "August", "September", "October", "November", "December"
   };
   
   /** Creates new form ModifyLog */
   public ModifyLog()
   {
      initComponents();
            
      insertDays(dayInCombo);
      insertDays(dayOutCombo);
      
      insertMonths(monthInCombo);
      insertMonths(monthOutCombo);
      
      insertYears(yearInCombo);
      insertYears(yearOutCombo);
      
      hourInSpinner.setModel(hourInSpinnerModel);
      hourOutSpinner.setModel(hourOutSpinnerModel);
      
      minuteInSpinner.setModel(minuteInSpinnerModel);
      minuteOutSpinner.setModel(minuteOutSpinnerModel);
      
      //updateFields();
   }
   
   private void insertDays(JComboBox box)
   {
      for (int i = 1; i < 32; i++)
      {
         box.addItem(i);
      }
   }
   
   private void insertMonths(JComboBox box)
   {
      for (int i = 0; i < monthNames.length; i++)
      {
         box.addItem(monthNames[i]);
      }
   }
   
   private void insertYears(JComboBox box)
   {
      Date now = new Date();
      Format format = new SimpleDateFormat("yyyy");
      int thisYear = Integer.parseInt(format.format(now));
      
      for (int i = thisYear - 5; i < thisYear + 5; i++)
      {
         box.addItem(i);
      }
   }
   
   private void selectItem(JComboBox box, int val)
   {
      for (int i = 0; i < box.getItemCount(); i++)
      {
         if (box.getItemAt(i).equals(val))
         {
            box.setSelectedIndex(i);
         }
      }
   }
   
   public void setLog(TimeLog aLog)
   {
      timeLog = aLog;
      
      updateFields();
   }

   public TimeLog getTimeLog()
   {
      return timeLog;
   }
   
   private void updateFields()
   {
      if (getTimeLog() != null)
      {
         if (getTimeLog().getClockOut() != null)
         {
            // Update Clock-In fields
            selectItem(dayInCombo, getTimeLog().getClockIn().getDay());
            monthInCombo.setSelectedItem(
                  monthNames[getTimeLog().getClockIn().getMonth() - 1]);
            selectItem(yearInCombo, getTimeLog().getClockIn().getYear());
            hourInSpinner.setValue(getTimeLog().getClockIn().getHours());
            minuteInSpinner.setValue(getTimeLog().getClockIn().getMinutes());

            // Update Clock-Out fields
            selectItem(dayOutCombo, getTimeLog().getClockOut().getDay());
            monthOutCombo.setSelectedItem(
                  monthNames[getTimeLog().getClockOut().getMonth() - 1]);
            selectItem(yearOutCombo, getTimeLog().getClockOut().getYear());
            hourOutSpinner.setValue(getTimeLog().getClockOut().getHours());
            minuteOutSpinner.setValue(getTimeLog().getClockOut().getMinutes());
         }
         else
         {
            JOptionPane.showMessageDialog(null,
                  "You cannot modify this entry!",
                  "Modify Entry Error",
                  JOptionPane.ERROR_MESSAGE);
         }
      }
   }
   
   public LogDate gatherClockIn()
   {
      LogDate tmp = new LogDate();
      
      Calendar clockIn = Calendar.getInstance();
      
      clockIn.set(
            Integer.parseInt(yearInCombo.getSelectedItem().toString()),
            monthInCombo.getSelectedIndex(),
            Integer.parseInt(dayInCombo.getSelectedItem().toString()),
            Integer.parseInt(hourInSpinner.getValue().toString()),
            Integer.parseInt(minuteInSpinner.getValue().toString()),
            getTimeLog().getClockIn().getSeconds());
      tmp.setTimeInMillis(clockIn.getTimeInMillis());
      
      return tmp;
   }
   
   public LogDate gatherClockOut()
   {
      LogDate tmp = new LogDate();
      
      Calendar clockOut = Calendar.getInstance();
      
      clockOut.set(
            Integer.parseInt(yearOutCombo.getSelectedItem().toString()),
            monthOutCombo.getSelectedIndex(),
            Integer.parseInt(dayOutCombo.getSelectedItem().toString()),
            Integer.parseInt(hourOutSpinner.getValue().toString()),
            Integer.parseInt(minuteOutSpinner.getValue().toString()),
            getTimeLog().getClockOut().getSeconds());
      tmp.setTimeInMillis(clockOut.getTimeInMillis());
      
      return tmp;
   }
   
   /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
   // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
   private void initComponents()
   {
      jLabel3 = new javax.swing.JLabel();
      jLabel4 = new javax.swing.JLabel();
      hourInSpinner = new javax.swing.JSpinner();
      minuteInSpinner = new javax.swing.JSpinner();
      jLabel5 = new javax.swing.JLabel();
      jLabel6 = new javax.swing.JLabel();
      hourOutSpinner = new javax.swing.JSpinner();
      minuteOutSpinner = new javax.swing.JSpinner();
      jSeparator1 = new javax.swing.JSeparator();
      saveButton = new javax.swing.JButton();
      cancelButton = new javax.swing.JButton();
      jPanel1 = new javax.swing.JPanel();
      dayOutCombo = new javax.swing.JComboBox();
      monthOutCombo = new javax.swing.JComboBox();
      yearOutCombo = new javax.swing.JComboBox();
      jPanel2 = new javax.swing.JPanel();
      dayInCombo = new javax.swing.JComboBox();
      monthInCombo = new javax.swing.JComboBox();
      yearInCombo = new javax.swing.JComboBox();

      setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
      setTitle("Modifying Log");
      setResizable(false);
      jLabel3.setText("Clock-In Date:");

      jLabel4.setText("Clock-In Time:");

      jLabel5.setText("Clock-Out Date:");

      jLabel6.setText("Clock-Out Time:");

      saveButton.setMnemonic('s');
      saveButton.setText("Save");
      saveButton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            saveButtonActionPerformed(evt);
         }
      });

      cancelButton.setMnemonic('c');
      cancelButton.setText("Cancel");
      cancelButton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            cancelButtonActionPerformed(evt);
         }
      });

      org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
      jPanel1.setLayout(jPanel1Layout);
      jPanel1Layout.setHorizontalGroup(
         jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(jPanel1Layout.createSequentialGroup()
            .add(dayOutCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 45, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(monthOutCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 105, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(yearOutCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 80, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
      );
      jPanel1Layout.setVerticalGroup(
         jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
            .add(dayOutCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .add(yearOutCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .add(monthOutCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
      );

      org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
      jPanel2.setLayout(jPanel2Layout);
      jPanel2Layout.setHorizontalGroup(
         jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(jPanel2Layout.createSequentialGroup()
            .add(dayInCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 45, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(monthInCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 105, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(yearInCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 80, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
      );
      jPanel2Layout.setVerticalGroup(
         jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
            .add(dayInCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .add(yearInCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .add(monthInCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
      );

      org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
         layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(layout.createSequentialGroup()
            .addContainerGap()
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(jLabel5)
               .add(org.jdesktop.layout.GroupLayout.TRAILING, jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
               .add(jLabel3)
               .add(layout.createSequentialGroup()
                  .add(jLabel4)
                  .add(12, 12, 12)
                  .add(hourInSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(minuteInSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
               .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                  .add(saveButton)
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(cancelButton))
               .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(layout.createSequentialGroup()
                  .add(jLabel6)
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(hourOutSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(minuteOutSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
               .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addContainerGap())
      );
      layout.setVerticalGroup(
         layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(layout.createSequentialGroup()
            .addContainerGap()
            .add(jLabel3)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(jLabel4)
               .add(hourInSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(minuteInSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .add(5, 5, 5)
            .add(jLabel5)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(jLabel6)
               .add(hourOutSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(minuteOutSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(cancelButton)
               .add(saveButton))
            .addContainerGap())
      );
      pack();
   }// </editor-fold>//GEN-END:initComponents

   private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cancelButtonActionPerformed
   {//GEN-HEADEREND:event_cancelButtonActionPerformed
      setVisible(false);
   }//GEN-LAST:event_cancelButtonActionPerformed

   private void saveButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveButtonActionPerformed
   {//GEN-HEADEREND:event_saveButtonActionPerformed
      TimeLog newLog = new TimeLog();
      newLog.setLogId(getTimeLog().getLogId());
      newLog.setClockIn(gatherClockIn());
      newLog.setClockOut(gatherClockOut());
            
      if (newLog.getClockIn() != null && newLog.getClockOut() != null)
      {
         if (newLog.getClockInTime() < newLog.getClockOutTime())
         {
            if (newLog.getClockOutTime() <= Math.floor(System.currentTimeMillis() / 1000))
            {
               MySQLDbIf.getInstance().updateLog(newLog);
               setVisible(false);
            }
            else
            {
               JOptionPane.showMessageDialog(null,
                     "Your clock-out time cannot be in the future!",
                     "Modify Log Error",
                     JOptionPane.ERROR_MESSAGE);
            }
         }
         else
         {
            JOptionPane.showMessageDialog(null,
                  "Your clock-in time cannot be after your clock-out time!",
                  "Modify Log Error",
                  JOptionPane.ERROR_MESSAGE);
         }
      }
      else
      {
         JOptionPane.showMessageDialog(null,
               "There was an error while saving your modifications.  Please try again.",
               "Modify Log Error",
               JOptionPane.ERROR_MESSAGE);
      }
   }//GEN-LAST:event_saveButtonActionPerformed
   
   /**
    * @param args the command line arguments
    */
   public static void main(String args[])
   {
      java.awt.EventQueue.invokeLater(new Runnable()
      {
         public void run()
         {
            new ModifyLog().setVisible(true);
         }
      });
   }

   public void setVisible(boolean b)
   {
      if (timeLog != null)
      {
         if (timeLog.getClockOut() == null)
         {
            super.setVisible(false);
         }
         else
         {
            super.setVisible(b);

            Point pt = WorkTimerGUI.getInstance().getLocation();
            setLocation((int) pt.getX() + WorkTimerGUI.getInstance().getWidth(), (int) pt.getY());
         }
      }
      else
      {
         super.setVisible(false);
      }
   }

   public void userChanged()
   {
      log.info("Trying to hide form...");
      super.setVisible(false);
   }
   
   // Variables declaration - do not modify//GEN-BEGIN:variables
   private javax.swing.JButton cancelButton;
   private javax.swing.JComboBox dayInCombo;
   private javax.swing.JComboBox dayOutCombo;
   private javax.swing.JSpinner hourInSpinner;
   private javax.swing.JSpinner hourOutSpinner;
   private javax.swing.JLabel jLabel3;
   private javax.swing.JLabel jLabel4;
   private javax.swing.JLabel jLabel5;
   private javax.swing.JLabel jLabel6;
   private javax.swing.JPanel jPanel1;
   private javax.swing.JPanel jPanel2;
   private javax.swing.JSeparator jSeparator1;
   private javax.swing.JSpinner minuteInSpinner;
   private javax.swing.JSpinner minuteOutSpinner;
   private javax.swing.JComboBox monthInCombo;
   private javax.swing.JComboBox monthOutCombo;
   private javax.swing.JButton saveButton;
   private javax.swing.JComboBox yearInCombo;
   private javax.swing.JComboBox yearOutCombo;
   // End of variables declaration//GEN-END:variables
   
}
